package cn.com.libertymutual.sp.service.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Sort;
import org.springframework.data.domain.Sort.Direction;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import cn.com.libertymutual.core.redis.util.RedisUtils;
import cn.com.libertymutual.core.util.Constants;
import cn.com.libertymutual.core.util.Current;
import cn.com.libertymutual.core.web.ServiceResult;
import cn.com.libertymutual.sp.bean.SysOperationLog;
import cn.com.libertymutual.sp.bean.TbSpClause;
import cn.com.libertymutual.sp.dao.ClauseDao;
import cn.com.libertymutual.sp.dao.OperationLogDao;
import cn.com.libertymutual.sp.service.api.ClauseService;

@Service
public class ClauseServiceImpl implements ClauseService {

	private Logger log = LoggerFactory.getLogger(getClass());
	@Autowired
	private ClauseDao clauseDao;

	@Autowired
	private OperationLogDao operationLogDao;
	@Resource
	private RedisUtils redisUtils;

	@Override
	public ServiceResult clauseList(String clauseTitle,String kindCode, int pageNumber, int pageSize) {

		ServiceResult sr = new ServiceResult();
		Sort sort = new Sort(Direction.ASC, "serialNumber");
		sr.setResult(clauseDao.findAll(new Specification<TbSpClause>() {
			@Override
			public Predicate toPredicate(Root<TbSpClause> root, CriteriaQuery<?> query, CriteriaBuilder cb) {

				List<Predicate> predicate = new ArrayList<Predicate>();
				if (StringUtils.isNotEmpty(clauseTitle)) {
					predicate.add(cb.like(root.get("clauseTitle").as(String.class), "%" + clauseTitle + "%"));
				}
				if (StringUtils.isNotEmpty(kindCode)) {
					predicate.add(cb.like(root.get("kindCode").as(String.class), "%" + kindCode + "%"));
				}
				Predicate[] pre = new Predicate[predicate.size()];
				return query.where(predicate.toArray(pre)).getRestriction();
			}
		}, PageRequest.of(pageNumber - 1, pageSize, sort)));
		return sr;
	}

	@Transactional(propagation = Propagation.REQUIRED) // 事务
	@Override
	public ServiceResult addClause(TbSpClause tbSpClause) {
		ServiceResult sr = new ServiceResult();
		SysOperationLog operLog = new SysOperationLog();
		operLog.setIP(Current.IP.get());
		operLog.setModule("条款管理");
		operLog.setOperationTime(new Date());
		operLog.setUserId(Current.userInfo.get().getUserId());
		List<TbSpClause> dbtbSpClause = clauseDao.findByKindCode(tbSpClause.getKindCode());
		if (null != tbSpClause.getId()) {// 修改
			if (dbtbSpClause.size() > 1) {
				sr.setResult("条款代码重复！");
				sr.setFail();
				return sr;
			} else {
				tbSpClause.setUpdateTime(new Date());
				operLog.setLevel("2");
				sr.setResult(clauseDao.save(tbSpClause));
				operLog.setContent("修改了id为" + tbSpClause.getId() + "的条款");
				operationLogDao.save(operLog);
			}
		} else {
			if (dbtbSpClause.size() >= 1) {
				sr.setResult("条款代码重复！");
				sr.setFail();
				return sr;
			} else {
				tbSpClause.setCreateTime(new Date());
				TbSpClause clause = clauseDao.save(tbSpClause);
				sr.setResult(clause);
				operLog.setLevel("1");
				operLog.setContent("添加了id为" + clause.getPlanId() + "的条款");
				operationLogDao.save(operLog);
			}
		}

		// 更新redis
		List<TbSpClause> dbTbSpClause = clauseDao.findAllClause();
		redisUtils.set(Constants.CLAUSE_INFO, dbTbSpClause);
		return sr;
	}

	@Transactional(propagation = Propagation.REQUIRED) // 事务
	@Override
	public ServiceResult removeClause(Integer id) {
		ServiceResult sr = new ServiceResult();
		TbSpClause DBTbSpClause = clauseDao.findById(id).get();
		SysOperationLog operLog = new SysOperationLog();
		operLog.setIP(Current.IP.get());
		operLog.setLevel("3");
		operLog.setModule("条款管理");
		operLog.setOperationTime(new Date());
		operLog.setUserId(Current.userInfo.get().getUserId());
		operLog.setContent("删除了planId为" + DBTbSpClause.getPlanId() + ",名称为" + DBTbSpClause.getClauseTitle() + "的条款");
		operationLogDao.save(operLog);
		clauseDao.deleteById(id);
		sr.setSuccess();
		// 更新redis
		List<TbSpClause> dbTbSpClause = clauseDao.findAllClause();
		redisUtils.set(Constants.CLAUSE_INFO, dbTbSpClause);
		return sr;
	}

	@Override
	public ServiceResult queryClause(String planId, String clauseTitle) {
		ServiceResult sr = new ServiceResult();
		try {
			List<TbSpClause> forTbSpClause = null;
			List<TbSpClause> redbTbSpClause = (List<TbSpClause>) redisUtils.get(Constants.CLAUSE_INFO);
			if (null != redbTbSpClause && redbTbSpClause.size() != 0) {
				log.info("---------redis数据库的------------");
				forTbSpClause = redbTbSpClause;
			} else {
				forTbSpClause = clauseDao.findAllClause();
				redisUtils.set(Constants.CLAUSE_INFO, forTbSpClause);
				log.info("---------访问数据库的------------");
			}
			List<TbSpClause> dbclause = new ArrayList<TbSpClause>();
			for (TbSpClause tbSpClause : forTbSpClause) {
				if (tbSpClause.getPlanId().indexOf(planId) != -1 && tbSpClause.getClauseTitle().equals(clauseTitle)) {
					dbclause.add(tbSpClause);
					break;
				}
			}
			sr.setResult(dbclause.get(0));
		} catch (Exception e) {
			log.info(e.getMessage());
			sr.setResult("数据异常！");
		}

		return sr;
	}

	// @Override
	// public ServiceResult queryClause(String planId, String clauseTitle) {
	// ServiceResult sr = new ServiceResult();
	// try {
	// List<TbSpClause> dbclause = clauseDao.findByPlanIdAndTitle(planId,
	// clauseTitle);
	// sr.setResult(dbclause.get(0));
	// } catch (Exception e) {
	// log.info(e.getMessage());
	// sr.setResult("数据异常！");
	// }
	//
	// return sr;
	// }

	@Override
	public ServiceResult queryClauseTitle(String planId) {
		ServiceResult sr = new ServiceResult();
		redisUtils.deletelike(Constants.CLAUSE_INFO);
		try {
			List<TbSpClause> forTbSpClause = null;
			List<TbSpClause> redbTbSpClause = (List<TbSpClause>) redisUtils.get(Constants.CLAUSE_INFO);
			if (null != redbTbSpClause && redbTbSpClause.size() != 0) {
				log.info("---------redis数据库的------------");
				forTbSpClause = redbTbSpClause;
			} else {
				forTbSpClause = clauseDao.findAllClause();
				redisUtils.set(Constants.CLAUSE_INFO, forTbSpClause);
				log.info("---------访问数据库的------------");
			}
			List<String> dbclause = new ArrayList<String>();
			for (TbSpClause tbSpClause : forTbSpClause) {
				if (tbSpClause.getPlanId().indexOf(planId) != -1) {
					dbclause.add(tbSpClause.getClauseTitle());
				}
			}
			sr.setResult(dbclause);
		} catch (Exception e) {
			log.info(e.getMessage());
			sr.setResult("数据异常！");
		}
		return sr;
	}

	// @Override
	// public ServiceResult queryClauseTitle(String planId) {
	// ServiceResult sr = new ServiceResult();
	// redisUtils.deletelike(Constants.CLAUSE_INFO);
	// try {
	// List<String> dbclause = clauseDao.findByPlanId(planId);
	// sr.setResult(dbclause);
	// } catch (Exception e) {
	// log.info(e.getMessage());
	// sr.setResult("数据异常！");
	// }
	// return sr;
	// }

	@Override
	public ServiceResult clauseTitleList() {
		ServiceResult sr = new ServiceResult();
		sr.setResult(clauseDao.findTitleList());
		return sr;
	}

}
